package com.wanlian.router.ui.main;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.smart.android.ui.app.IntentExtra;
import com.smart.android.utils.UIUtils;
import com.wanlian.router.R;
import com.wanlian.router.bean.FileType;
import com.wanlian.router.event.RefreshEvent;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.internal.INetCallBack;
import com.wanlian.router.ui.WlBaseActivity;
import com.wanlian.router.ui.main.yun.YunFileTranslateActivity;
import com.wanlian.router.ui.main.yun.YunMusicFragment;
import com.wanlian.router.ui.main.yun.YunPictureFragment;
import com.wanlian.router.ui.main.yun.YunVideoFragment;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Hyu on 2018/9/3.
 * Email: fvaryu@163.com
 */
public class YunFilesActivity extends WlBaseActivity {

    private static final int FILE_REQUEST_CODE = 101;
    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.viewpager)
    ViewPager mViewPager;
    @BindView(R.id.tv_upload)
    TextView tv_upload;
    private int mType;

    public static void go(Context context, int which) {
        Intent intent = new Intent(context, YunFilesActivity.class);
        intent.putExtra(IntentExtra.EXTRA_TYPE, which);
        context.startActivity(intent);
    }

    public static String getFilePathByUri(Context context, Uri uri) {
        String path = null;
        // 以 file:// 开头的
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            path = uri.getPath();
            return path;
        }
        // 以 content:// 开头的，比如 content://media/extenral/images/media/17766
        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()) && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    if (columnIndex > -1) {
                        path = cursor.getString(columnIndex);
                    }
                }
                cursor.close();
            }
            return path;
        }
        // 4.4及之后的 是以 content:// 开头的，比如 content://com.android.providers.media.documents/document/image%3A235700
        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (DocumentsContract.isDocumentUri(context, uri)) {
                if (isExternalStorageDocument(uri)) {
                    // ExternalStorageProvider
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
                    if ("primary".equalsIgnoreCase(type)) {
                        path = Environment.getExternalStorageDirectory() + "/" + split[1];
                        return path;
                    }
                } else if (isDownloadsDocument(uri)) {
                    // DownloadsProvider
                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                            Long.valueOf(id));
                    path = getDataColumn(context, contentUri, null, null);
                    return path;
                } else if (isMediaDocument(uri)) {
                    // MediaProvider
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{split[1]};
                    path = getDataColumn(context, contentUri, selection, selectionArgs);
                    return path;
                }
            }
        }
        return null;
    }

    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    @Override
    protected int layout() {
        return R.layout.activity_yun_files;
    }

    @Override
    public void initUI() {
        super.initUI();
        setTitle("云盘");

        setNextImage(R.drawable.image_yun_file_upload);
        setNextClickLisener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                redirectActivity(YunFileTranslateActivity.class);
            }
        });

        mViewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                switch (i) {
                    case 0: {
                        return YunPictureFragment.newInstance();
                    }
                    case 1: {
                        return YunVideoFragment.newInstance();
                    }
                    case 2: {
                        return YunMusicFragment.newInstance();
                    }
                }
                return null;
            }

            @Override
            public int getCount() {
                return 3;
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return "照片";
                    case 1:
                        return "视频";
                    case 2:
                        return "音乐";
                }
                return null;
            }
        });

        mTabLayout.setupWithViewPager(mViewPager);

        mType = getIntent().getIntExtra(IntentExtra.EXTRA_TYPE, 0);
        mViewPager.setCurrentItem(mType);
        mViewPager.setOffscreenPageLimit(3);

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mType = tab.getPosition();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        UIUtils.setIndicator(mTabLayout, 45, 45);
    }

    @Override
    public void initData() {
        super.initData();

    }

    @OnClick(R.id.tv_upload)
    void upload() {
        if (mType > 0) {
            showToast("暂不支持");
            return;
        }
        Intent intent = new Intent();
        switch (mType) {
            case 0: {
                intent.setType("image/*");//选择图片
                intent.setAction(Intent.ACTION_GET_CONTENT);
            }
            break;
            case 1: {
//                intent.setType("video/*");
                if ("meizu".equalsIgnoreCase(Build.BRAND)) {
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    intent.setDataAndType(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "video/*");
                } else {
                    //  魅族手机使用此方式 不会显示视频,, 华为不可用上面的方式
                    intent.setAction(Intent.ACTION_PICK);
                    intent.setData(MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                }
            }
            break;
            case 2: {
                intent.setType("audio/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
            }
            break;
        }
        //intent.setType(“image/*”);//选择图片
        //intent.setType(“audio/*”); //选择音频
        //intent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
        //intent.setType(“video/*;image/*”);//同时选择视频和图片
//        intent.setType("*/ * ");//无类型限制
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, FILE_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Activity.RESULT_OK == resultCode) {

            if (requestCode == FILE_REQUEST_CODE) {
                if (data == null) {
                    return;
                }
                Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
                if (uri == null) {
                    showToast("无效文件");
                    return;
                }
                String path = null;
//                if (mType != 0) {
                ContentResolver cr = this.getContentResolver();
                Cursor cursor = cr.query(uri, null, null, null, null);
                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                    }
                    cursor.close();
                }

//                }

                if (path == null) {
                    path = getFilePathByUri(getActivity(), uri);
                }
                if (path == null) {
                    return;
                }
                final File file = new File(path);

//                UploadServer.addTask(new UpTask(0L, file.getName(), file.getPath(), 0, file.length(), FileType.Picture.ordinal()));
                NetWorkingClient.getInstance().uploadFile(getActivity(), file, new INetCallBack() {
                    @Override
                    public void onFinish(ResponseData response, @Nullable Object o) {
                        if (response.isSuccess()) {

                            int type = mType == 0 ? 1 : mType == 2 ? 2 : 0;
                            NetWorkingClient.getInstance().putFileToYunSys(getActivity(),
                                    file.getName(), file.length() / 1024.f / 1024.f, type, response.getUrl(), new INetCallBack() {
                                        @Override
                                        public void onFinish(ResponseData response, @Nullable Object o) {
                                            if (response.isSuccess()) {
                                                showToast("上传成功");

                                                EventBus.getDefault().post(new RefreshEvent(FileType.Picture));
                                            } else {
                                                showToast(response.getMessage());
                                            }
                                        }
                                    });
                        } else {
                            showToast(response.getMessage());
                        }
                    }
                });
            }

        }
    }

}


